var sort_key; // 排序关键字
var sort; // 排序方式
var page; // 当前页码
var pageSize = 10; // 页面大小
var questionId;
var answerSet = {}; // answer集合

var anonymous='匿名用户';
// 填充问题页面
function getQuestion() {
	var questionId = $.getUrlParam("questionId");
	if (questionId) {
		$.get(G_BASE_URL + "/getQuestion.do", {
			questionId : questionId
		}, function(result) {
			if (result.errno != 1) {
				$.alert(result.err);
			} else {
				if (result.rsm) {
					// 设置问题标题和内容
					var question = result.rsm.question;
					$("#question_name").html(question.questionName);
					$("#question_details").html(question.questionDesc);
					$("#question_time").html(question.createTime);

					// 设置问题状态
					$("#question_last_motify").html(question.lastMotify);
					$("#question_attention_count")
							.html(result.rsm.attentionNum);
					// 设置问题关注按钮
					var question_id = question.questionId;
					var is_attention = result.rsm.isAttentionQuestion;
					var active = 'aw-active';
					var attention = '关注';
					if (is_attention) {
						active = '';
						attention = '取消关注';
					}

					var template = Hogan
							.compile(HR_TEMPLATE.attention_question).render({
								'question_id' : question_id,
								'active' : active,
								'attention' : attention
							});

					$("#question_follow").html(template);

					// 设置提问者信息
					var template = Hogan.compile(HR_TEMPLATE.question_user)
							.render({
								'user_id' : result.rsm.user.userId,
								
								'user_img' : result.rsm.user.photo
							});
					$("#side_bar_user").html(template);

					var active = 'aw-active';
					var attention = '关注';
					if (result.rsm.isAttentionUser) {
						active = '';
						attention = '取消关注';
					}
					var template = Hogan.compile(
							HR_TEMPLATE.question_attention_user).render({
						'user_id' : result.rsm.user.userId,
						'active' : active,
						'user_nick':result.rsm.user.nickName,
						'attention' : attention
					});
					$("#side_bar_atttion_user").html(template);

					// 设置问题的话题标签
					if (result.rsm.topics) {
						var topics = result.rsm.topics;
						var topic_names = '';
						var topicHtml = '';
//						topics.forEach(function(topic) {
//							topic_names+= topic.topicName + ',';
//							var template = Hogan.compile(
//									HR_TEMPLATE.question_topic).render({
//								'topic_name' : topic.topicName,
//								'topic_id':topic.topicId,
//							});
//							topicHtml += template;
//						});
						$.each(topics,function(i,topic){
							topic_names+= topic.topicName + ',';
							var template = Hogan.compile(
									HR_TEMPLATE.question_topic).render({
								'topic_name' : topic.topicName,
								'topic_id':topic.topicId,
							});
							topicHtml += template;
						});
						$('#question_topic_editor').html(topicHtml);
						// 根据话题获取推荐人物
						getQuestionRecommendPeople(topic_names);
					}

					// 设置回答问题的id
					$('#answer_question_id').val(questionId);
					getQuestionAnswersCount(questionId);
					
					// 添加问题回答
					getQuestionAnswers(questionId, 'vote', 'desc');
				}
			}
		}, "json");
	}
}
//获取问题答案数量

function getQuestionAnswersCount(_questionId){
	$.get(G_BASE_URL + "/getQuestionAnswersCount.do", {
		questionId : _questionId,
	}, function(result) {
		if (result.errno != 1) {
			$.alert(result.err);
		} else {
			// 设置回复数量
			$('#answer_num').html('共有'+result.rsm + '个回复');
		}
	},'json');
}

// 获取第一页问题答案
function getQuestionAnswers(_questionId, _sort_key, _sort) {
	// 初始化变量
	questionId = _questionId;
	sort_key = _sort_key;
	sort = _sort;
	page = 1;
	answerSet = {};
	
	$.get(G_BASE_URL + "/getQuestionAnswers.do", {
		questionId : _questionId,
		sort_key : _sort_key,
		sort : _sort,
		page : 1,
		pageSize : pageSize
	}, function(result) {
		if (result.errno != 1) {
			$.alert(result.err);
		} else {
//			设置更多按钮
			if(result.rsm.length == 0){
				$("#answer_more").text("暂时没有答案");
				return;
			}
			$("#answer_more").attr("onclick","getMoreQuestionAnswers();");
			$("#answer_more").text("加载更多答案...");
			// 添加answer内容
			var answerHtml = '';
			$.each(result.rsm, function(i, item) {
				var user = item.user;
				var answer = item.answer;
				// 加入问题集合
				answerSet[answer.answerId] = true;
				var comment_text = '添加评论';
				if(answer.commentNum > 0){
					comment_text = '共有' + answer.commentNum +'条评论';
				}
				var user_url = G_BASE_URL + '/people.do?uid=' + user.userId;
				if(user.userId == anonymous){
					user_url='#';
				}
				var template = Hogan.compile(HR_TEMPLATE.question_answer)
						.render({
							'user_id' : user.userId,
							'user_nick':user.nickName,
							'user_url':  user_url, 
							'user_img' : user.photo,
							'answer_id' : answer.answerId,
							'introduce' : answer.introduce,
							'vote_num' : answer.voteCount,
							'answer_content' : answer.answerContext,
							'comment_num' : answer.commentNum,
							'comment_text':comment_text,
							'answer_time' : answer.createTime,
						});
				answerHtml += html_entity_decode(template);
			});
			$('#answer_list').html(answerHtml);
		}
	}, 'json');
}

// 加载更多问题答案
function getMoreQuestionAnswers() {
//	loading
	$("#answer_more").addClass("loading");
	$("#answer_more").removeAttr("onclick");
	// 页码++
	page += 1;
	$.get(G_BASE_URL + "/getQuestionAnswers.do", {
		questionId : questionId,
		sort_key : sort_key,
		sort : sort,
		page : page,
		pageSize : pageSize
	}, function(result) {
		$("#answer_more").removeClass("loading");
		$("#answer_more").attr("onclick","getMoreQuestionAnswers();");
		if (result.errno != 1) {
			$.alert(result.err);
		} else {
			
			if(result.rsm.length == 0){
				$("#answer_more").text("没有更多回答");
				$("#answer_more").removeAttr("onclick");
				return;
			}
			// 添加answer内容
			var answerHtml ='';
			var answerContainer = $('#answer_list');
			$.each(result.rsm, function(i, item) {
				var user = item.user;
				var answer = item.answer;
				
				if (!answerSet[answer.answerId]) {
					var comment_text = '添加评论';
					if(answer.commentNum > 0){
						comment_text = '共有' + answer.commentNum +'条评论';
					}
					var user_url = G_BASE_URL + '/people.do?uid=' + user.userId;
					if(user.userId == anonymous){
						user_url='#';
					}
					var template = Hogan.compile(HR_TEMPLATE.question_answer)
							.render({
								'user_id' : user.userId,
								'user_nick':user.nickName,
								'user_url':  user_url, 
								'user_img' : user.photo,
								'answer_id' : answer.answerId,
								'introduce' : answer.introduce,
								'vote_num' : answer.voteCount,
								'answer_content' : answer.answerContext,
								'comment_num' : answer.commentNum,
								'comment_text':comment_text,
								'answer_time' : answer.createTime,
							});
					answerHtml += html_entity_decode(template);
				}
			});
			answerContainer.append(answerHtml);
		}
	}, 'json');
}
// 获取某个话题下的推荐回答人物
function getQuestionRecommendPeople(topics) {
	$.get(G_BASE_URL + '/ajax/findTopicRecommendPeople.do', {
		topics : topics
	}, function(result) {
		if (result.errno != 1) {
			$.alert(result.err);
		} else {
			if (result.rsm) {
				// 防止话题过长显示不全
				var inviteHtml = '<ul style="max-height:120px">';
				$.each(result.rsm, function(i, item) {
					var template = Hogan.compile(
							HR_TEMPLATE.question_invite_user).render({
						'user_id' : item.user.userId,
						'user_nick':item.user.nickName,
						'user_img' : item.user.photo,
						'topic_name' : item.topic,
						'vote_num' : item.voteNum
					});
					inviteHtml += template;
				});
				inviteHtml += '</ul>';
				$('.aw-invite-box .aw-mod-body').html(inviteHtml);
				// 初始化邀请数据
				init_invite();
			}

		}
	});

}

// 初始化邀请数据
function init_invite() {
	// 邀请初始化
	$('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li').hide();

	for (var i = 0; i < 3; i++) {
		$('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li').eq(i)
				.show();
	}

	// 长度小于3翻页隐藏
	if ($('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li').length <= 3) {
		$('.aw-question-detail-title .aw-invite-box .aw-mod-footer').hide();
	} else {
		// 邀请上一页
		$('.aw-question-detail-title .aw-invite-box .prev')
				.click(
						function() {
							if (!$(this).hasClass('active')) {
								var attr = [], li_length = $('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li').length;
								$
										.each(
												$('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li'),
												function(i, e) {
													if ($(this).is(':visible') == true) {
														attr.push($(this)
																.index());
													}
												});
								$(
										'.aw-question-detail-title .aw-invite-box .aw-mod-body ul li')
										.hide();
								$
										.each(
												attr,
												function(i, e) {
													if (attr.join('') == '123'
															|| attr.join('') == '234') {
														$(
																'.aw-question-detail-title .aw-invite-box .aw-mod-body ul li')
																.eq(0).show();
														$(
																'.aw-question-detail-title .aw-invite-box .aw-mod-body ul li')
																.eq(1).show();
														$(
																'.aw-question-detail-title .aw-invite-box .aw-mod-body ul li')
																.eq(2).show();
													} else {
														$(
																'.aw-question-detail-title .aw-invite-box .aw-mod-body ul li')
																.eq(e - 3)
																.show();
													}

													if (e - 3 == 0) {
														$(
																'.aw-question-detail-title .aw-invite-box .prev')
																.addClass(
																		'active');
													}
												});
								$(
										'.aw-question-detail-title .aw-invite-box .next')
										.removeClass('active');
							}
						});

		// 邀请下一页
		$('.aw-question-detail-title .aw-invite-box .next')
				.click(
						function() {
							if (!$(this).hasClass('active')) {
								var attr = [], li_length = $('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li').length;
								$
										.each(
												$('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li'),
												function(i, e) {
													if ($(this).is(':visible') == true) {
														attr.push($(this)
																.index());
													}
												});
								$
										.each(
												attr,
												function(i, e) {
													if (e + 3 < li_length) {
														$(
																'.aw-question-detail-title .aw-invite-box .aw-mod-body ul li')
																.eq(e).hide();
														$(
																'.aw-question-detail-title .aw-invite-box .aw-mod-body ul li')
																.eq(e + 3)
																.show();
													}
													if (e + 4 == $('.aw-question-detail-title .aw-invite-box .aw-mod-body ul li').length) {
														$(
																'.aw-question-detail-title .aw-invite-box .next')
																.addClass(
																		'active');
													}
												});
								$(
										'.aw-question-detail-title .aw-invite-box .prev')
										.removeClass('active');
							}
						});
	}
}

// 赞成投票
function agreeVote(element, user_name, answer_id) {
	if ($(element).parents('.vote-container').find('#agree_vote').hasClass(
			"active")
			|| $(element).parents('.vote-container').find('#disagree_vote')
					.hasClass("active")) {
		$.alert("您已投过票，不能重复投票");
		return;
	}

	$.post(G_BASE_URL + '/ajax/answerVote.do', {
		answer_id : answer_id,
		value : 1
	}, function(result) {
		if (result.errno != 1) {
			$.alert("投票错误，请稍后再试");
		} else {
			if (result.rsm.status == 'voted') {

				if (result.rsm.type == '1') {
					$(element).parents('.vote-container').find('#agree_vote')
							.addClass("active");
				} else {
					$(element).parents('.vote-container')
							.find('#disagree_vote').addClass("active");
				}
				$.alert("您之前已投过票，不能重复投票");
				return;
			}
			$(element).addClass("active");
			var num = parseInt($(element).parents('.aw-item').find(
					'.aw-vote-bar-count').html());
			$(element).parents('.aw-item').find('.aw-vote-bar-count').html(
					num + 1);
		}
	}, 'json');
}
// 反对投票
function disagreeVote(element, user_name, answer_id) {
	if ($(element).parents('.vote-container').find('#agree_vote').hasClass(
			"active")
			|| $(element).parents('.vote-container').find('#disagree_vote')
					.hasClass("active")) {
		$.alert("您已投过票，不能重复投票");
		return;
	}

	$.post(G_BASE_URL + '/ajax/answerVote.do', {
		answer_id : answer_id,
		value : -1
	}, function(result) {
		if (result.errno != 1) {
			$.alert("投票错误，请稍后再试");
		} else {
			if (result.rsm.status == 'voted') {

				if (result.rsm.type == '1') {
					$(element).parents('.vote-container').find('#agree_vote')
							.addClass("active");
				} else {
					$(element).parents('.vote-container')
							.find('#disagree_vote').addClass("active");
				}
				$.alert("您之前已投过票，不能重复投票");
				return;
			}
			$(element).addClass("active");
			var num = parseInt($(element).parents('.aw-item').find(
					'.aw-vote-bar-count').html());
			$(element).parents('.aw-item').find('.aw-vote-bar-count').html(
					num - 1);
		}
	}, 'json');
}

// 答案排序
function answer_sort(element, sort_key) {
	var questionId = $.getUrlParam("questionId");
	$(element).parents(".aw-reset-nav-tabs").find("#time")
			.removeClass("active");
	$(element).parents(".aw-reset-nav-tabs").find("#vote")
			.removeClass("active");
	$(element).parents(".aw-reset-nav-tabs").find("#" + sort_key).addClass(
			"active");
	var sort = '';
	if (sort_key == 'time') {
		if ($(element).attr('type') == 'desc') {
			$(element).attr('type', 'asc');
			sort = 'asc';
			$(element).find("i").attr('class', 'fa fa-caret-up');
		} else {
			$(element).attr('type', 'desc');
			sort = 'desc';
			$(element).find("i").attr('class', 'fa fa-caret-down');
		}
	}
	getQuestionAnswers(questionId, sort_key, sort);

}

// 用户点击保存评论后，重新加载评论数据
function hr_comments_form_processer(result) {
	$.each($('a._save_comment.disabled'), function(i, e) {

		$(e).attr('onclick', $(this).attr('_onclick')).removeAttr('_onclick')
				.removeClass('disabled').removeClass('_save_comment');
	});

	if (result.errno != 1) {
		$.alert(result.err);
	} else {
		hr_reload_comments_list(result.rsm.item_id, result.rsm.item_id,
				result.rsm.type_name);

		$(
				'#aw-comment-box-' + result.rsm.type_name + '-'
						+ result.rsm.item_id + ' form input').val('');
		$(
				'#aw-comment-box-' + result.rsm.type_name + '-'
						+ result.rsm.item_id + ' form textarea').val('');
	}
}
// 重新加载评论数据
function hr_reload_comments_list(item_id, element_id, type_name) {
	$('#aw-comment-box-' + type_name + '-' + element_id + ' .aw-comment-list')
			.html(
					'<p align="center" class="aw-padding10"><i class="aw-loading"></i></p>');

	$.get(G_BASE_URL + '/ajax/getAnswerComments.do?answer_id=' + item_id
			+ '&question_id=' + $.getUrlParam("questionId"), function(result) {
		var commentHtml;
		if (!result.rsm) {
			commentHtml = '<div align="center" class="aw-padding10">'
					+ _t('暂无评论') + '</div>';
		} else {
			commentHtml = '<ul>';
			$.each(result.rsm, function(i, item) {
				var template = Hogan.compile(HR_TEMPLATE.answer_comment_item)
						.render({
							'user_id' : item.user.userId,
							'user_nick':item.user.nickName,
							'user_img' : item.user.photo,
							'create_time' : item.comment.createTime,
							'comment' : item.comment.commentContex,
						});
				commentHtml += template;
			});
		}
		$(
				'#aw-comment-box-' + type_name + '-' + element_id
						+ ' .aw-comment-list').html(commentHtml);
	});
}